<?php
namespace app\api\controller\food;

use app\api\controller\food\Controller;
use app\api\model\Applet as AppletModel;
use app\api\model\Page as PageModel;
use app\api\model\Setting  as SettingModel;
use app\api\model\Wechat  as WechatModel;
use app\api\model\Config;
use hema\wechat\Driver as Wechat;

/**
 * 小程序
 */
class Applet extends Controller
{
    /**
     * 小程序基础信息
     */
    public function base()
    {
        $applet = AppletModel::detail();
        $page = PageModel::getHome()['page_data']['array']; //获取DIY页面数据
		$applet['navbar'] = $page['page'];
        $applet['tabbar'] = $page['tabbar'];
        $applet['postpaid'] = SettingModel::getItem('payment')['postpaid'];//获取后付费模式
        $applet['other'] = SettingModel::getItem('other');
        $config = Config::detail();
        $applet['component_appid'] = $config['app_id'];//第三方应用ID
        if($wechat = WechatModel::detail()){
            $applet['wechat_appid'] = $wechat['app_id'];//公众号ID
        }
        $web = SettingModel::getItem('web',0);
        $applet['copyright'] = $web['copyright'];
        $helper = SettingModel::getItem('foodhelp',0);
        $applet['helper_appid'] = $helper['app_id']; //助手小程序appid
        return $this->renderSuccess(compact('applet'));
    }

    /**
     * 微信公众号获取权限验证配置
     */
    public function signPackage($url)
    {
        $wx = new Wechat;
        if($ticket = $wx->getTicket($this->applet_id)){
            $signPackage['nonceStr'] = md5(time());
            $signPackage['jsapi_ticket'] = $ticket;
            $signPackage['timestamp'] = time();
            $signPackage['url'] = $url;
            //签名步骤一：按字典序排序参数
            ksort($signPackage);
            //格式化参数格式化成url参数
            $buff = '';
            foreach ($signPackage as $k => $v) {
                if ($k != 'sign' && $v != '' && !is_array($v)) {
                    $buff .= $k . '=' . $v . '&';
                }
            }
            $buff = trim($buff, '&');
            $signPackage['signature'] = sha1($buff);
            $wxapp = AppletModel::detail($this->applet_id);
            $signPackage['app_id'] = $wxapp['app_id'];
            return $this->renderSuccess(compact('signPackage'));
        }
        return $this->renderError('ticket获取失败');
    }

}
